<?php

# Session Start
session_name('SID');
session_start();

class module {

	var $zam;
	
	function main()
	{		
		switch ($this->zam->data['get']['app'])
		{
			default:
			case 'signup':
				$this->register();
				break;
			case 'validate':
				$this->validate();
				break;
			case 'authusr':
				$this->authusername();
				break;
				
		}
	}
	
	#==================================
	# Registration form
	#==================================
	function register()
	{
		# POST fields
		$username = $this->zam->data['post']['username'];
		$password = $this->zam->data['post']['password'];
		$confpass = $this->zam->data['post']['confpass'];
		$email = $this->zam->data['post']['email'];
		$confemail = $this->zam->data['post']['confemail'];
		$captcha = $this->zam->data['post']['captcha'];
		$head = $this->zam->tags->script('prototype.js') . $this->zam->tags->script('regauth.js');
		
		if ( !$this->zam->data['post']['register'] )
		{
			$this->zam->skin->set_vars( array(
				'title'		=>	'Register',
				'head'		=>	$head,
				'subtemp'	=>	'register.tpl'
			) );
		}
		else
		{
			$result = $this->zam->sql->construct( array(
				'action'	=>	'select',
				'fields'	=>	'username',
				'db'		=>	constant('DB_MEMBERS'),
				'where'		=>	"username = '{$this->zam->data['post']['username']}'",
				'limit'		=>	1
			) );
			
			$usrntaken = ( $this->zam->sql->num_rows($query) == 1 ) ? true : false;
			
			if ( strlen($username) < 4 )
			{
				$usrerror = '<img src="./images/error.png" alt="" /> Invalid username';
				$error = true;
			}
			
			if ( $usrntaken )
			{
				$usrerror = '<img src="./images/error.png" alt="" /> Username taken';
				$error = true;
			}
			
			if ( ( strlen($password) < 6 ) or ( $password != $confpass ) )
			{
				$passerror = '<img src="./images/error.png" alt="" /> Invalid password';
				$error = true;
			}
			
			if ( ( !preg_match('/^([a-z0-9\.\-_]+)@([a-z0-9\.\-]+)\.([a-z]{2,5})$/i', $email) ) or ( $email != $confemail ) )
			{
				$emerror = '<img src="./images/error.png" alt="" /> Invalid email address';
				$error = true;
			}
			
			if ( $captcha != $_SESSION['captcha'] )
			{
				$codeerror = '<img src="./images/error.png" alt="" /> Invalid code';
				$error = true;
			}
			
			if ( $this->zam->data['post']['terms'] != 'yes' )
			{
				$termerror = '<img src="./images/error.png" alt="" /> You must agree to these terms';
				$error = true;
			}
			
			if ( !$error )
			{
				$salt = substr( sha1( uniqid( rand(), true ) ), 0, 9 );
				$passhash = sha1( md5( $password . $salt ) );
				$loginkey = str_replace( '=', '', base64_encode( strrev( crypt( $password ) ) ) );
				$urlname = trim( preg_replace( '/([^a-z0-9\-_])/', '', strtolower($username) ) );
				
				$data = array(
					'id'			=> NULL,
					'username'		=> $username,
					'urlname'   	=> $urlname,
					'email'     	=> $email,
					'passhash'  	=> $passhash,
					'pass_salt' 	=> $salt,
					'login_key'		=> $loginkey,
					'joindate'		=> time(),
					'joinip'		=> $_SERVER['REMOTE_ADDR'],
					'logindate'		=> 0,
					'mgroup'		=> 2
				);
				
				$result = $this->zam->sql->construct( array(
					'action'	=>	'insert',
					'db'		=>	constant('DB_MEMBERS'),
					'insert'	=>	$data
				) );
				
				$result2 = $this->zam->sql->construct( array(
					'action'	=>	'insert',
					'db'		=>	constant('DB_EXTRA'),
					'insert'	=>	array( 'member_id' => mysql_insert_id() )
				) );
				
				# Optimize
				$this->zam->sql->query(sprintf("OPTIMIZE TABLE %s", constant('DB_MEMBERS')));

				
				# Email
				$continue = "Welcome to Zameleon. To continue check your email, {$email}, to validate your account.";
				$message = "Welcome to Zameleon,<br />\nTo continue with the validation of your account, follow this link below:<br />\n<br />\n<a href=\"{$url}register?app=validate&authkey={$loginkey}\">{$this->zam->url}register?app=validate&authkey={$loginkey}</a><br />\n<br />\nIf you are having problems validating your account please contact our help support at help@zameleon.com<br />\n<br />\nSincerely,<br />\nZameleon Support Team";
				$this->zam->email->send($email, 'Validate Your Zameleon Account', $message);
				
				$this->zam->skin->set_vars( array(
					'title'		=>	'Registered',
					'content'	=>	$continue
				) );
			}
			else
			{
				# Error			
				$this->zam->skin->set_vars( array(
					'usrerror'	=>	$usrerror,
					'passerror'	=>	$passerror,
					'emerror'	=>	$emerror,
					'codeerror'	=>	$codeerror,
					'termerror'	=>	$termerror,
					'title'		=>	'Register',
					'head'		=>	$head,
					'subtemp'	=>	'register.tpl'
				) );
			}
		}
		
		$this->zam->skin->display('template.tpl');
	}
		
	#==================================
	# Validate user
	#==================================
	function validate()
	{
		if ( ( !empty($this->zam->data['get']['mid']) ) and ( !empty($this->zam->data['get']['authkey']) ) )
		{
			$where = sprintf("id = %d AND login_key = '%s'",
				intval($this->zam->data['get']['mid']),
				$this->zam->data['get']['authkey']
			);
			
			$query = $this->zam->sql->construct( array(
				'action'	=>	'update',
				'db'		=>	constant('DB_MEMBERS'),
				'set'		=>	array( 'mgroup' => 3 ),
				'where'		=>	$where,
				'limit'		=>	1
			) );
			
			# You're broke...
			header("Pragma: no-cache");
			header("Expires: -1");
			header("Cache-Control: no-cache");
			
			if ( $this->zam->sql->affected_rows() == 1 )
			{	
				$this->zam->skin->set_vars( array(
					'title'		=>	'Activated',
					'content'	=>	"Your account has been validated. <a href=\"{$this->zam->url}\">Login</a>."
				) );
				
				# Make photo directory
				$userid = intval($this->zam->data['get']['mid']);
				@mkdir("./uploads/user.$userid/");
				@chmod("./uploads/user.$userid/", 0777);
			}
			else
			{
				# Error
				$this->zam->skin->set_vars( array(
					'title'		=>	'Error',
					'content'	=>	"Error while attempting to validate your account. Check the <a href=\"{$this->zam->url}faq\">FAQs</a> if this problem continues to happen."
				) );
			}
		}
		else
		{
			# Error
			$this->zam->skin->set_vars( array(
				'title'		=>	'Error',
				'content'	=>	"Error while attempting to validate your account. Check the <a href=\"{$this->zam->url}faq\">FAQs</a> if this problem continues to happen."
			) );
		}
		
		$this->zam->skin->display('template.tpl');
	}
	
	#==================================
	# AJAX username validator
	#==================================
	function authusername()
	{
		$result = $this->zam->sql->construct( array(
			'action'	=>	'select',
			'fields'	=>	'username',
			'db'		=>	constant('DB_MEMBERS'),
			'where'		=>	"username = '{$this->zam->data['get']['usrname']}'",
			'limit'		=>	1
		) );
		
		print ( $this->zam->sql->num_rows($result) == 1 ) ? 1 : 0;
	}
	
}

?>